import api from '@/common/api.js'
// import wx from 'weixin-js-sdk'

const baseUrl = "https://yunluh5.bigchun.com/api"

export function formatDate(date, format) {
	let time = {
		"M+": date.getMonth() + 1,
		"d+": date.getDate(),
		"h+": date.getHours(),
		"m+": date.getMinutes(),
		"s+": date.getSeconds(),
		"q+": Math.floor((date.getMonth() + 3) / 3),
		"M+": date.getMonth() + 1,
		"S+": date.getMilliseconds()
	}
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for (let k in time) {
		if (new RegExp('(' + k + ')').test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? time[k] : ('00' + time[k]).substr(('' + time[k])
				.length))
		}
	}
	return format;
}

export function getToken() {
	function hexToBase64(str) {
		return btoa(String.fromCharCode.apply(null,
			str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")
		));
	}
	return new Promise((resolve, reject) => {
		api.getAccessToken({
			HospitalId: hexToBase64(md5(config.healthAppId))
		}).then(res => {
			if (res.Code === 0) {
				resolve(res.Result)
				uni.setStorageSync('accessToken', res.Result)
			} else {
				reject()
			}
		}).catch(err => {
			reject()
		})
	})
}

export const axios = {
	get({
		url,
		data,
		urlType
	}) {
		return request({
			method: 'get',
			url,
			data,
			urlType
		})
	},
	post({
		url,
		urlType,
		data,
		type
	}) {
		return request({
			method: 'post',
			url,
			data,
			urlType,
			type
		})
	}
}

function request(options) {
	return new Promise((resolve, reject) => {
		if (!options.url) {
			uni.showToast({
				title: 'url必填',
				icon: 'none',
				mask: true,
				duration: 1000
			})
			reject('url不能为空')
			return
		}
		let token = uni.getStorageSync('token') || '78d6c485-8e36-4391-8cbe-9771ddad0831'
		options.url = baseUrl + options.url
		options.header = {
			'content-type': options.type || 'application/x-www-form-urlencoded',
		}
		// if (uni.getStorageSync('token')) {
		// 	options.header['token'] = uni.getStorageSync('token')
		// }
		options.header['token'] = token
		options.timeout = 20000
		options.complete = (response) => {
			if (response.statusCode == 200) {
				resolve(response.data)
			} else {
				if (response.statusCode && response.errMsg) {
					uni.showModal({
						title: "提示",
						content: JSON.stringify(response.data.errors) + response.data.status,
						showCancel: false
					});
				} else {
					uni.showModal({
						title: "提示",
						content: '网络连接失败,请检查网络',
						showCancel: false
					});
				}
				reject(response)
			}
		}
		let params = {
			url: '',
			method: '',
			data: '',
			timeout: 20000,
			header: '',
			complete: ''
		}
		copyObject(options, params)
		uni.request(params)
	})
}

// export function pay(params) {
// 	return new Promise((resolve, reject) => {
// 		wx.requestPayment({
// 			timeStamp: params.TimeStamp + "",
// 			nonceStr: params.NonceStr,
// 			signType: 'RSA',
// 			package: params.Package,
// 			paySign: params.PaySign,
// 			success: (res) => {
// 				resolve(res)
// 			},
// 			fail: (err) => {
// 				reject(err)
// 			}
// 		})
// 	})
// }

export function uuid(len, radix) {
	var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	var uuid = [],
		i;
	radix = radix || chars.length;
	if (len) {
		for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
	} else {
		var r;
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
	}
	return uuid.join('');
}

function copyObject(old, newO) {
	let a = Object.keys(newO)
	a.forEach(item => {
		newO[item] = old[item]
	})
}